<template>
  <div class="rich-text-editor">
    <!-- 工具栏 -->
    <div class="editor-toolbar">
      <el-button-group>
        <el-button 
          size="small" 
          @click="insertLink"
          title="插入链接"
        >
          <el-icon><Link /></el-icon>
          插入链接
        </el-button>
        <el-button 
          size="small" 
          @click="insertExternalLink"
          title="插入外部链接"
        >
          <el-icon><Connection /></el-icon>
          外部链接
        </el-button>
        <el-button 
          size="small" 
          @click="insertImage"
          title="插入图片"
        >
          <el-icon><Picture /></el-icon>
          插入图片
        </el-button>
      </el-button-group>
      
      <el-button-group class="ml-2">
        <el-button 
          size="small" 
          @click="formatBold"
          title="加粗"
        >
          <strong>B</strong>
        </el-button>
        <el-button 
          size="small" 
          @click="formatItalic"
          title="斜体"
        >
          <em>I</em>
        </el-button>
        <el-button 
          size="small" 
          @click="formatUnderline"
          title="下划线"
        >
          <u>U</u>
        </el-button>
      </el-button-group>
    </div>
    
    <!-- 编辑器 -->
    <div class="editor-container">
      <textarea 
        ref="textareaRef"
        v-model="content"
        :placeholder="placeholder"
        :rows="rows"
        @input="handleInput"
        @select="handleTextSelect"
        class="editor-textarea"
      />
    </div>
    
    <!-- 预览区域 -->
    <div v-if="showPreview" class="editor-preview">
      <h4>预览效果：</h4>
      <div class="preview-content" v-html="content"></div>
    </div>

    <!-- 插入链接对话框 -->
    <el-dialog
      v-model="linkDialogVisible"
      title="插入链接"
      width="500px"
    >
      <el-form :model="linkForm" label-width="80px">
        <el-form-item label="链接类型">
          <el-radio-group v-model="linkForm.type">
            <el-radio value="internal">内部链接</el-radio>
            <el-radio value="external">外部链接</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="链接文本">
          <el-input v-model="linkForm.text" placeholder="请输入链接显示文本" />
        </el-form-item>
        
        <el-form-item v-if="linkForm.type === 'internal'" label="内部页面">
          <el-select v-model="linkForm.internalPath" placeholder="选择内部页面" style="width: 100%">
            <el-option label="首页" value="/" />
            <el-option label="报名入口" value="/admission/registration" />
            <el-option label="入围查询" value="/admission/qualified" />
            <el-option label="缴费链接" value="/admission/payment/links" />
            <el-option label="院校电话" value="/schools/phone" />
            <el-option label="院校排名" value="/schools/ranking" />
            <el-option label="院校官网" value="/schools/website" />
            <el-option label="专业介绍" value="/schools/majors" />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="linkForm.type === 'external'" label="外部网址">
          <el-input v-model="linkForm.externalUrl" placeholder="请输入完整的网址，如：https://example.com" />
        </el-form-item>
        
        <el-form-item label="打开方式">
          <el-radio-group v-model="linkForm.target">
            <el-radio value="_self">当前窗口</el-radio>
            <el-radio value="_blank">新窗口</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="linkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertLink">确认插入</el-button>
      </template>
    </el-dialog>

    <!-- 插入图片对话框 -->
    <el-dialog
      v-model="imageDialogVisible"
      title="插入图片"
      width="400px"
    >
      <el-form :model="imageForm" label-width="80px">
        <el-form-item label="图片地址">
          <el-input v-model="imageForm.url" placeholder="请输入图片网址" />
        </el-form-item>
        <el-form-item label="替代文本">
          <el-input v-model="imageForm.alt" placeholder="图片描述（可选）" />
        </el-form-item>
        <el-form-item label="图片宽度">
          <el-input v-model="imageForm.width" placeholder="如：300px 或 100%（可选）" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="imageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsertImage">确认插入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Link, Connection, Picture } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容...'
  },
  rows: {
    type: Number,
    default: 15
  },
  showPreview: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

// 响应式数据
const content = ref(props.modelValue)
const textareaRef = ref(null)
const linkDialogVisible = ref(false)
const imageDialogVisible = ref(false)

// 选中的文本信息
const selectedText = reactive({
  text: '',
  start: 0,
  end: 0
})

// 链接表单
const linkForm = reactive({
  type: 'internal',
  text: '',
  internalPath: '',
  externalUrl: '',
  target: '_blank'
})

// 图片表单
const imageForm = reactive({
  url: '',
  alt: '',
  width: ''
})

// 监听内容变化
watch(content, (newVal) => {
  emit('update:modelValue', newVal)
})

watch(() => props.modelValue, (newVal) => {
  content.value = newVal
})

// 方法
const handleInput = () => {
  // 自动触发更新
}

const handleTextSelect = () => {
  const textarea = textareaRef.value
  if (textarea) {
    selectedText.text = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
    selectedText.start = textarea.selectionStart
    selectedText.end = textarea.selectionEnd
  }
}

const insertTextAtCursor = (text) => {
  const textarea = textareaRef.value
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const value = textarea.value
  
  content.value = value.substring(0, start) + text + value.substring(end)
  
  // 更新光标位置
  setTimeout(() => {
    const newPosition = start + text.length
    textarea.setSelectionRange(newPosition, newPosition)
    textarea.focus()
  }, 0)
}

const insertLink = () => {
  linkForm.text = selectedText.text || ''
  linkForm.type = 'internal'
  linkForm.internalPath = ''
  linkForm.externalUrl = ''
  linkForm.target = '_self'
  linkDialogVisible.value = true
}

const insertExternalLink = () => {
  linkForm.text = selectedText.text || ''
  linkForm.type = 'external'
  linkForm.internalPath = ''
  linkForm.externalUrl = ''
  linkForm.target = '_blank'
  linkDialogVisible.value = true
}

const confirmInsertLink = () => {
  if (!linkForm.text) {
    ElMessage.warning('请输入链接文本')
    return
  }
  
  let linkHtml = ''
  
  if (linkForm.type === 'internal') {
    if (!linkForm.internalPath) {
      ElMessage.warning('请选择内部页面')
      return
    }
    linkHtml = `<a href="${linkForm.internalPath}" target="${linkForm.target}">${linkForm.text}</a>`
  } else {
    if (!linkForm.externalUrl) {
      ElMessage.warning('请输入外部网址')
      return
    }
    // 确保外部链接有协议
    let url = linkForm.externalUrl
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
      url = 'https://' + url
    }
    linkHtml = `<a href="${url}" target="${linkForm.target}" rel="noopener noreferrer">${linkForm.text}</a>`
  }
  
  insertTextAtCursor(linkHtml)
  linkDialogVisible.value = false
  ElMessage.success('链接插入成功')
}

const insertImage = () => {
  imageForm.url = ''
  imageForm.alt = ''
  imageForm.width = ''
  imageDialogVisible.value = true
}

const confirmInsertImage = () => {
  if (!imageForm.url) {
    ElMessage.warning('请输入图片地址')
    return
  }
  
  let imageHtml = `<img src="${imageForm.url}"`
  
  if (imageForm.alt) {
    imageHtml += ` alt="${imageForm.alt}"`
  }
  
  if (imageForm.width) {
    imageHtml += ` style="width: ${imageForm.width}"`
  }
  
  imageHtml += ' />'
  
  insertTextAtCursor(imageHtml)
  imageDialogVisible.value = false
  ElMessage.success('图片插入成功')
}

const formatBold = () => {
  if (selectedText.text) {
    const boldText = `<strong>${selectedText.text}</strong>`
    insertTextAtCursor(boldText)
  } else {
    insertTextAtCursor('<strong></strong>')
  }
}

const formatItalic = () => {
  if (selectedText.text) {
    const italicText = `<em>${selectedText.text}</em>`
    insertTextAtCursor(italicText)
  } else {
    insertTextAtCursor('<em></em>')
  }
}

const formatUnderline = () => {
  if (selectedText.text) {
    const underlineText = `<u>${selectedText.text}</u>`
    insertTextAtCursor(underlineText)
  } else {
    insertTextAtCursor('<u></u>')
  }
}
</script>

<style lang="scss" scoped>
.rich-text-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  
  .editor-toolbar {
    background: #f5f7fa;
    padding: 8px 12px;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .editor-container {
    position: relative;
    
    .editor-textarea {
      width: 100%;
      border: none;
      outline: none;
      resize: vertical;
      padding: 12px;
      font-size: 14px;
      line-height: 1.6;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      
      &::placeholder {
        color: #c0c4cc;
      }
    }
  }
  
  .editor-preview {
    border-top: 1px solid #dcdfe6;
    padding: 12px;
    background: #fafafa;
    
    h4 {
      margin: 0 0 12px 0;
      color: #606266;
      font-size: 14px;
    }
    
    .preview-content {
      max-height: 200px;
      overflow-y: auto;
      background: white;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      
      :deep(a) {
        color: #409eff;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      :deep(img) {
        max-width: 100%;
        height: auto;
        border-radius: 4px;
      }
    }
  }
}

.ml-2 {
  margin-left: 8px;
}
</style>